package mediadisplay.viewerarea 
{
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Anders Figenschow selvfølgelig
	 */
	public class Background extends Sprite
	{
		private var request:URLRequest;
		private var loader:Loader;
		private var _fillWindow:Boolean;
		private var _viewerArea:ViewerArea;
		
		public function Background(viewerArea:ViewerArea) 
		{
			_viewerArea = viewerArea;
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			addEventListener(Event.REMOVED_FROM_STAGE, cleanup);
			loader = new Loader;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function imageLoaded(e:Event):void 
		{
			addChild(loader);
			if (_fillWindow) {
				loader.width = 1024;
				loader.scaleY = loader.scaleX;
			}
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void 
		{
			trace("can't load background image: " + e);
		}
		
		public function setBackgroundImage(url:String, fillWindow:Boolean = false):void {
			try 
			{
				loader.unloadAndStop(true);
				removeChild(loader);
			}catch (err:Error)
			{
				// lol
				trace("can't clean up in this bitch.");
			}
			
			_fillWindow = fillWindow;
			request = new URLRequest(url);
			loader.load(request);
			trace("loading background image: " +url);
		}
		
		private function cleanup(e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, cleanup);
			if (loader) {
				loader.unloadAndStop(true);
				removeChild(loader);				
			}
		}
		
	}

}